<template>
  <div class="self-page-select">
    <el-select
      v-model="selectValue"
      filterable
      :loading="loading"
      :placeholder="placeholder"
      :clearable="clearable"
      :disabled="disabled"
      @change="onChange"
    >
      <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
      </el-option>
    </el-select>
    <el-button v-if="!hiddenBtn" type="text" @click="goSetting">去配置</el-button>
  </div>
</template>

<script>
import * as api from '@/const/api'
import { configureSelfPageEdit } from '@/const/path'

export default {
  props: {
    // v-model 绑定的值
    value: {
      type: [String, Array],
      default: '',
    },
    // 占位符
    placeholder: {
      type: String,
      default: '请输入',
    },
    // 是否可以清空选项
    clearable: {
      type: Boolean,
      default: true,
    },
    // change事件
    change: {
      type: Function,
      default: null,
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false,
    },
    // 隐藏去配置按钮
    hiddenBtn: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      options: [],
    }
  },
  computed: {
    selectValue: {
      get() {
        return this.value
      },
      set(val) {
        // 触发v-model绑定值更新
        this.$emit('input', val)
      },
    },
  },
  mounted() {
    this.goPage()
  },
  methods: {
    async goPage() {
      try {
        this.loading = true

        const { code, msg, data } = await this.$axios.$get(api.solutionContentList)

        if (+code !== 200) {
          throw new Error(msg || '操作失败')
        }
        this.options = data.map((item) => ({
          label: item.title,
          value: item.id,
        }))
      } catch (err) {
        err.message && this.$message.error(err.message)
      } finally {
        this.loading = false
      }
    },
    goSetting() {
      this.$router.push({
        path: `${configureSelfPageEdit}0`,
      })
    },
    // 监听change事件
    onChange(val) {
      // 返回当前项json对象，方便关联其他表单处理
      this.$emit('change', val)
    },
  },
}
</script>

<style lang="less" scoped>
.self-page-select {
  display: flex;

  .el-select {
    flex: 1;
    margin-right: 10px;
  }
}
</style>
